#include <glib.h>
#include <SDL.h>
#include "racanhack.h"
#include "task.h"
#include "video.h"
#include "cave.h"
#include "player.h"
#include "stair.h"
#include "floor.h"
#include "los.h"

void stair_trans_state(state (*fp)(struct _task *task), struct _stair *stair)
{
  if (stair->task != NULL) {
    stair->task->alive = FALSE;
  };
  stair->task = task_add(fp, stair);
}
 
struct _stair *is_stair(struct _coord coord)
{
  GList *li;
  struct _stair *stair;
  for (li = g_list_first(curf->stair_list); li != NULL; li = g_list_next(li)) {
    stair = (struct _stair *)li->data;
    if ((stair->coord.x == coord.x) && (stair->coord.y == coord.y)) return stair;
  };
  return NULL;
}

void stair_init()
{
  SDL_Surface *s;
  SDL_Rect r;
  s = video_bmp_load("bmp/stair_idle.bmp");
  r.w = SPRITE_W; r.h = SPRITE_H;
  r.x = SPRITE_W * 0; r.y = SPRITE_H * 0;
  surface_stair_idle[STAIR_TYPE_DOWN] = video_crop(s, &r);
  r.x = SPRITE_W * 1; r.y = SPRITE_H * 0;
  surface_stair_idle[STAIR_TYPE_UP] = video_crop(s, &r);
  SDL_FreeSurface(s);
}

void stair_free()
{
  SDL_FreeSurface(surface_stair_idle[STAIR_TYPE_DOWN]);
  SDL_FreeSurface(surface_stair_idle[STAIR_TYPE_UP]);
}

struct _stair *stair_add(int type)
{
  struct _stair *stair;
  stair = my_new(struct _stair, 1);
  stair->coord = rand_coord();
  stair->type = type;
  stair->tutorial_floor = FALSE;
  stair->root_floor = curf;
  stair->dest_stair = NULL;
  stair->sprite = NULL;
  stair->task = NULL;
  curf->stair_list = g_list_append(curf->stair_list, stair);
  return(stair);
}

state stair_idle(struct _task *task)
{
  struct _stair *stair;
  stair = (struct _stair *)task->pointer[0];
  if (is_los_onsight(stair->coord)) {
    stair->sprite->surface = surface_stair_idle[stair->type];
  } else {
    stair->sprite->surface = NULL;
  };

}
